package com.mfoyou.agent.web.utils.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 此类用于发送短信验证码
 *
 * @author yp-tc-m-2681
 */
public class SmsUtils_2 {

    private static final Logger logger = LoggerFactory.getLogger(SmsUtils_2.class);

    private static String SIGN_NAME = "友达速帮";
    private static String APP_KEY = "LTAI7VqvbhIr5qK0";
    private static String APP_SECRET = "qCoateJHuH5yZDZJTbOBiiym8NoPVq";
    private static String APP_SENDSMS = "https://eco.taobao.com/router/rest";
    static final String tempcode = "SMS_156277795";

    /**
     * 此方法用于正式环境短信验证码发送
     *
     * @param phoneNumber   手机号码
     * @param code
     * @param extenId
     * @param type
     * @return  true表示发送成功，false表示发送失败
     */
    public static int sendSMSCode(String phoneNumber, String code, String extenId, int type) {
        logger.info("bengin send " + phoneNumber + ",code=" + code + ",extenId=" + extenId);
        TaobaoClient client = new DefaultTaobaoClient(APP_SENDSMS, APP_KEY, APP_SECRET);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        if (extenId != null) req.setExtend(extenId);
        req.setSmsType("normal");
        req.setSmsFreeSignName(SIGN_NAME);
        req.setSmsParamString("{\"number\":\"" + code + "\"}");
        req.setRecNum(phoneNumber);
        logger.info("message code = " + tempcode);
        req.setSmsTemplateCode(tempcode);
        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e1) {
            logger.error("發送短信異常", e1);
            return -4;
        }
        String ret = rsp.getBody();
        logger.info(ret);
        int error_ret = 0;
        try {
            JSONObject object = JSON.parseObject(ret);
            JSONObject sO = object.getJSONObject("alibaba_aliqin_fc_sms_num_send_response");
            if (sO == null) {
                if (type == 0) {
                    return sendSMSCode(phoneNumber, code, extenId, -99);
                }
                return object.getJSONObject("error_response").getInteger(code);
            }
            error_ret = 0;
        } catch (Exception e) {
            logger.error(ret, e);
            return -32;
        }
        return error_ret;
    }

    @Test
    public void test() {
        try {
            int sendSMSCode = sendSMSCode("13658024608", "123233", "", 1);
            System.out.println(sendSMSCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
